<template>
  <AdVxeModal
    v-bind="$attrs"
    :destroyOnClose="true"
    @register="registerModal"
    :id="'org-role-transfer-modal'"
    :showCancel="false"
    :showOk="false"
    :close-func="handleClose"
    @ok="handleOk"
  >
    <template #insertFooter>
      <a-button type="default" @click="handleCancel" :loading="loadingRef">
        {{ cancelText }}
      </a-button>
      <Authority :value="okAuthorityCode" v-if="okAuthority === true">
        <a-button type="primary" @click="handleOk" :loading="loadingRef">
          {{ okText }}
        </a-button>
      </Authority>
      <a-button type="primary" @click="handleOk" v-if="okAuthority !== true" :loading="loadingRef">
        {{ okText }}
      </a-button>
    </template>

    <Transfer
      :dataSource="dataSource"
      :targetKeys="targetKeys"
      :showSearch="search"
      :filterOption="filterOption"
      :showSelectAll="false"
      @change="onChange"
      style="height: 100%"
    >
      <template
        #children="{
          direction,
          filteredItems,
          selectedKeys,
          disabled: listDisabled,
          onItemSelectAll,
          onItemSelect,
        }"
      >
        <Table
          :rowSelection="
            getRowSelection({
              disabled: listDisabled,
              selectedKeys,
              onItemSelectAll,
              onItemSelect,
            })
          "
          :columns="direction === 'left' ? leftColumns : rightColumns"
          :dataSource="filteredItems"
          size="small"
          :style="{ pointerEvents: listDisabled ? 'none' : null }"
          :customRow="
            ({ key, disabled: itemDisabled }) => ({
              onClick: () => {
                if (itemDisabled || listDisabled) {
                  return;
                }
                if (direction === 'left') {
                  onItemSelect(key, !selectedKeys.includes(key));
                }
              },
            })
          "
          @resize-column="handleResizeColumn"
        />
      </template>
    </Transfer>
  </AdVxeModal>
</template>
<script lang="ts">
  import type { PropType } from 'vue';
  import { difference } from 'lodash-es';
  import { defineComponent, ref, h } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { Transfer, Table, Checkbox } from 'ant-design-vue';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { Authority } from '@/components/Authority';

  import { RoleOrganizationNode } from '@/api/identity/admin/role/model';

  import { isFunction } from '@/utils/is';
  import { propTypes } from '@/utils/propTypes';

  const { t } = useI18n();

  interface DataSource extends RoleOrganizationNode {
    key: string;
    title: string;
    description: string;
    disabled: boolean;
  }

  const leftTableColumns = [
    // {
    //   dataIndex: 'Id',
    //   title: t('entity.idTitle'),
    //   resizable: true,
    //   ellipsis: true,
    //   width: 180,
    // },
    {
      dataIndex: 'Name',
      title: t('routes.system.identity.role.nameTitle'),
      resizable: true,
      ellipsis: true,
      width: 150,
    },
    {
      dataIndex: 'Remark',
      title: t('routes.system.identity.role.remarkTitle'),
      resizable: true,
      ellipsis: true,
      width: 100,
    },
    // {
    //   dataIndex: 'IsAdmin',
    //   title: t('routes.system.identity.role.isAdminTitle'),
    //   resizable: true,
    //   ellipsis: true,
    //   width: 120,
    // },
    // {
    //   dataIndex: 'IsLocked',
    //   title: t('entity.lockable.isLockedTitle'),
    //   resizable: true,
    //   ellipsis: true,
    //   width: 0,
    // },
  ];
  const rightTableColumns = [
    // {
    //   dataIndex: 'Id',
    //   title: t('entity.idTitle'),
    //   resizable: true,
    //   ellipsis: true,
    //   width: 100,
    // },
    {
      dataIndex: 'Name',
      title: t('routes.system.identity.role.nameTitle'),
      resizable: true,
      ellipsis: true,
      width: 150,
    },
    {
      dataIndex: 'Remark',
      title: t('routes.system.identity.role.remarkTitle'),
      resizable: true,
      ellipsis: true,
      width: 100,
    },
    // {
    //   dataIndex: 'IsAdmin',
    //   title: t('routes.system.identity.role.isAdminTitle'),
    //   resizable: true,
    //   ellipsis: true,
    //   width: 180,
    // },
    // {
    //   dataIndex: 'IsLocked',
    //   title: t('entity.lockable.isLockedTitle'),
    //   resizable: true,
    //   ellipsis: true,
    //   width: 0,
    // },
    {
      dataIndex: 'Administrator',
      title: t('routes.system.identity.organization.administratorTitle'),
      resizable: true,
      ellipsis: true,
      width: 90,
      align: 'center',
      customRender: ({ record }) => {
        return h(Checkbox, {
          checked: record.Administrator === true,
          onChange(e: any) {
            // console.log('checked', e?.target?.checked);
            record.Administrator = e?.target?.checked;
          },
        });
      },
    },
    {
      dataIndex: 'Leader',
      title: t('routes.system.identity.organization.leaderTitle'),
      resizable: true,
      ellipsis: true,
      width: 70,
      align: 'center',
      customRender: ({ record }) => {
        return h(Checkbox, {
          checked: record.Leader === true,
          onChange(e: any) {
            record.Leader = e?.target?.checked;
          },
        });
      },
    },
  ];

  export default defineComponent({
    name: 'OrgRoleTransferModal',
    components: { AdVxeModal, Transfer, Table, Authority },
    props: {
      /** 显示搜索框 */
      search: propTypes.bool.def(true),
      /** 取消按钮文本 */
      cancelText: propTypes.string.def(t('common.cancelText')),
      /** 关闭回调，返回true关闭窗体 */
      closeFunc: {
        type: Function as PropType<
          (targetKeys: string[], roleNodes: RoleOrganizationNode[], record: any) => Promise<boolean>
        >,
        default: null,
      },
      /** 确认按钮文本 */
      okText: propTypes.string.def(t('common.okText')),
      /** 确认按钮权限（默认不开启） */
      okAuthority: propTypes.bool.def(false),
      /** 确认按钮权限代码（按钮权限开启有效） */
      okAuthorityCode: {
        type: [Number, Array, String] as PropType<string | string[]>,
        default: '',
      },
      /** 确定回调，返回true关闭窗体 */
      okFunc: {
        type: Function as PropType<
          (targetKeys: string[], roleNodes: RoleOrganizationNode[], record: any) => Promise<boolean>
        >,
        default: null,
      },
    },
    setup(props) {
      // const { t } = useI18n();
      const targetKeys = ref<string[]>([]);
      const dataSource = ref<DataSource[]>([]);

      const leftColumns = ref<any[]>(leftTableColumns);
      const rightColumns = ref<any[]>(rightTableColumns);
      const recordRef = ref<any>();

      //#region "加载状态"
      const loadingRef = ref(false);
      /** 开启加载状态 */
      function openLoading() {
        changeLoading(true);
        setModalProps({ okLoading: true, cancelLoading: true });
        loadingRef.value = true;
      }
      /** 关闭加载状态 */
      function closeLoading() {
        changeLoading(false);
        setModalProps({ okLoading: false, cancelLoading: false });
        loadingRef.value = false;
      }
      //#endregion

      const onChange = (nextTargetKeys: string[]) => {
        targetKeys.value = nextTargetKeys;
      };

      const getRowSelection = ({
        disabled,
        selectedKeys,
        onItemSelectAll,
        onItemSelect,
      }: Record<string, any>) => {
        return {
          getCheckboxProps: (item: Record<string, string | boolean>) => ({
            disabled: disabled || item.disabled,
          }),
          onSelectAll(selected: boolean, selectedRows: Record<string, string | boolean>[]) {
            const treeSelectedKeys = selectedRows
              .filter((item) => !item.disabled)
              .map(({ key }) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, selectedKeys)
              : difference(selectedKeys, treeSelectedKeys);
            onItemSelectAll(diffKeys, selected);
          },
          onSelect({ key }: Record<string, string>, selected: boolean) {
            onItemSelect(key, selected);
          },
          selectedRowKeys: selectedKeys,
        };
      };

      const [registerModal, { setModalProps, closeModal, changeLoading }] = useModalInner(
        async (data) => {
          changeLoading(true);
          try {
            // console.log('data', data);
            targetKeys.value = [];
            dataSource.value = [];
            recordRef.value = null;
            if (data.roleNodes && data.roleNodes.length > 0) {
              dataSource.value = data.roleNodes;
              targetKeys.value = dataSource.value
                .filter((item) => item.IsChecked === true)
                .map((item) => item.Id.toString());
              dataSource.value.forEach((item) => {
                item.key = item.Id.toString();
                item.title = item.Name;
                item.description = item.Remark;
                item.disabled = false;
              });
              // console.log('dataSource', dataSource.value);
            }
            if (data.record) {
              recordRef.value = data.record;
            }
          } finally {
            changeLoading(false);
          }
        },
      );

      /** 处理关闭事件 */
      async function handleClose() {
        openLoading();

        const { closeFunc } = props;
        try {
          if (closeFunc && isFunction(closeFunc)) {
            //重新设置数据源选中值
            resetDataSource();
            const result = await closeFunc(targetKeys.value, dataSource.value, recordRef.value);
            // console.log('closeFunc', result);
            return result;
          }
        } finally {
          closeLoading();
        }
        // console.log('handleClose', true);
        return true;
      }
      /** 处理关闭按钮 */
      async function handleCancel() {
        let innerClose = true;
        openLoading();
        const { closeFunc } = props;
        try {
          if (closeFunc && isFunction(closeFunc)) {
            //重新设置数据源选中值
            resetDataSource();
            innerClose = await closeFunc(targetKeys.value, dataSource.value, recordRef.value);
            // console.log('closeFunc', innerClose);
          }
        } finally {
          closeLoading();
        }
        // console.log('handleCancel', innerClose);
        if (innerClose) {
          closeModal();
        }
      }
      /** 处理确定按钮 */
      async function handleOk() {
        openLoading();
        const { okFunc } = props;
        try {
          if (okFunc && isFunction(okFunc)) {
            //重新设置数据源选中值
            resetDataSource();
            const canClose = await okFunc(targetKeys.value, dataSource.value, recordRef.value);
            if (canClose) {
              closeModal();
            }
          } else {
            closeModal();
          }
        } finally {
          closeLoading();
        }
      }

      /** 重新设置数据源选中值 */
      function resetDataSource() {
        dataSource.value.forEach((item) => {
          item.IsChecked = targetKeys.value.indexOf(item.key) >= 0;
        });
      }

      /** 筛选配置 */
      const filterOption = (inputValue: string, option: any) => {
        return (
          option.key.toLowerCase().indexOf(inputValue.toLowerCase()) > -1 ||
          option.title.toLowerCase().indexOf(inputValue.toLowerCase()) > -1 ||
          option.description.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
        );
      };

      return {
        t,
        loadingRef,
        registerModal,
        handleClose,
        handleCancel,
        handleOk,
        dataSource,
        targetKeys,
        leftColumns,
        rightColumns,
        onChange,
        getRowSelection,
        filterOption,
        handleResizeColumn: (w: any, col: any) => {
          col.width = w;
        },
      };
    },
  });
</script>
